import { initParticlesJS } from './particles.js';

/**
 * 钓鱼天堂 - 主逻辑脚本
 * 处理用户认证、页面公共功能和会话管理
 */

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查用户登录状态
    checkLoginStatus();
    
    // 初始化示例数据（如果不存在）
    initializeExampleData();
    
    // 初始化粒子效果
    initParticlesJS();
    
    // 设置正在开发中的功能
    setupDevelopmentFeatures();
    
    // 初始化通用页面交互
    setupCommonInteractions();
});

/**
 * 检查用户登录状态并更新界面
 */
function checkLoginStatus() {
    const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
    
    if (user) {
        // 用户已登录，更新界面
        if (document.getElementById('user-auth-section')) {
            document.getElementById('user-auth-section').classList.add('hidden');
        }
        
        if (document.getElementById('user-info-section')) {
            document.getElementById('user-info-section').classList.remove('hidden');
            if (document.getElementById('username')) {
                document.getElementById('username').textContent = user.nickname || '未知用户';
            }
            if (document.getElementById('user-avatar')) {
                document.getElementById('user-avatar').src = user.avatar || 'https://picsum.photos/40/40';
                
                // 添加点击头像跳转到个人中心功能
                document.getElementById('user-avatar').addEventListener('click', function(event) {
                    event.preventDefault();
                    window.location.href = 'info.html';
                });
                
                // 添加悬停效果
                document.getElementById('user-avatar').classList.add('cursor-pointer');
                document.getElementById('user-avatar').title = "查看个人中心";
            }
            
            // 添加退出登录事件监听
            if (document.getElementById('logout-btn')) {
                document.getElementById('logout-btn').addEventListener('click', function() {
                    logout();
                });
            }
        }
    } else {
        // 用户未登录
        if (document.getElementById('user-auth-section')) {
            document.getElementById('user-auth-section').classList.remove('hidden');
        }
        
        if (document.getElementById('user-info-section')) {
            document.getElementById('user-info-section').classList.add('hidden');
        }
    }
    
    // 更新购物车数量
    updateCartCount();
}

/**
 * 用户登出
 */
function logout() {
    localStorage.removeItem('currentUser');
    window.location.reload();
}

/**
 * 更新购物车数量显示
 */
function updateCartCount() {
    const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
    const cartCountElement = document.getElementById('cart-count');
    
    if (cartCountElement) {
        cartCountElement.textContent = cart.length;
    }
}

/**
 * 显示通知
 * @param {string} message - 通知消息
 * @param {string} type - 通知类型 ('success', 'error', 'warning', 'info')
 * @param {number} duration - 通知显示时长，毫秒
 */
function showNotification(message, type = 'success', duration = 3000) {
    // 查找或创建通知容器
    let notification = document.getElementById('notification');
    
    if (!notification) {
        notification = document.createElement('div');
        notification.id = 'notification';
        notification.className = 'fixed bottom-4 right-4 p-4 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50';
        document.body.appendChild(notification);
    }
    
    // 设置通知样式
    notification.textContent = message;
    
    // 根据类型设置背景颜色
    notification.className = 'fixed bottom-4 right-4 p-4 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50';
    
    switch (type) {
        case 'error':
            notification.classList.add('bg-red-500', 'text-white');
            break;
        case 'warning':
            notification.classList.add('bg-yellow-500', 'text-white');
            break;
        case 'info':
            notification.classList.add('bg-blue-500', 'text-white');
            break;
        default:
            notification.classList.add('bg-green-500', 'text-white');
    }
    
    // 显示通知
    notification.classList.remove('hidden', 'translate-y-20', 'opacity-0');
    
    // 设定时间后隐藏
    setTimeout(() => {
        notification.classList.add('translate-y-20', 'opacity-0');
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 300);
    }, duration);
}

/**
 * 初始化示例数据
 * 如果本地存储中不存在数据，则创建示例数据
 */
function initializeExampleData() {
    // 初始化用户数据
    if (!localStorage.getItem('users')) {
        const initialUsers = [
            {
                id: '1',
                username: 'admin',
                email: 'admin@example.com',
                password: 'admin123',
                registrationDate: '2025-01-01T00:00:00.000Z',
                avatar: 'https://picsum.photos/id/64/200/200',
                role: 'admin',
                bio: '网站管理员，热爱钓鱼20年，专注于淡水钓鱼技巧分享。',
                experience: '20年',
                favoriteSpots: ['太湖', '洞庭湖', '鄱阳湖'],
                points: 9999
            },
            {
                id: '2',
                username: '钓鱼达人',
                email: 'fish@example.com',
                password: 'password123',
                registrationDate: '2025-01-15T00:00:00.000Z',
                avatar: 'https://picsum.photos/id/22/200/200',
                role: 'user',
                bio: '爱钓鱼，爱生活。专攻鲫鱼、鲤鱼等淡水鱼类。',
                experience: '5年',
                favoriteSpots: ['西湖', '洞庭湖'],
                points: 520
            }
        ];
        
        localStorage.setItem('users', JSON.stringify(initialUsers));
    }
    
    // 初始化商品数据
    if (!localStorage.getItem('products')) {
        const initialProducts = [
            {
                id: 1,
                name: '专业碳素鱼竿',
                price: 299,
                originalPrice: 399,
                image: 'https://picsum.photos/400/300?rod',
                category: 'rods',
                featured: true,
                hot: true,
                description: '超轻超硬碳素材质，28调节多功能鱼竿，适合各种钓鱼场景，手感舒适，性能稳定。'
            },
            {
                id: 2,
                name: '金属轴承渔轮',
                price: 199,
                originalPrice: 259,
                image: 'https://picsum.photos/400/300?reel',
                category: 'reels',
                featured: true,
                hot: true,
                description: '12+1轴承设计，超强耐磨金属材质，高速比5.2:1，轻松应对大鱼。'
            },
            {
                id: 3,
                name: '仿生软饵套装',
                price: 89,
                originalPrice: 119,
                image: 'https://picsum.photos/400/300?bait',
                category: 'lures',
                featured: true,
                hot: false,
                description: '30款多彩软饵，高度仿真设计，柔软有弹性，气味持久。适合淡水和海水环境。'
            },
            {
                id: 4,
                name: '多功能钓箱',
                price: 359,
                originalPrice: 459,
                image: 'https://picsum.photos/400/300?box',
                category: 'accessories',
                featured: true,
                hot: true,
                description: '高强度工程塑料材质，多层设计，大容量储物空间。内置可调节隔板，防水防潮。'
            }
        ];
        
        localStorage.setItem('products', JSON.stringify(initialProducts));
    }
    
    // 初始化论坛帖子数据
    if (!localStorage.getItem('forumPosts')) {
        const initialPosts = [
            {
                id: "1",
                title: "分享：昨天在太湖钓获的大鲫鱼",
                content: `<p>大家好，昨天我去太湖边钓鱼，收获颇丰！其中最大的一条鲫鱼有近2斤重，真是太兴奋了！</p>
                        <p>在此分享一下我的钓鱼技巧：</p>
                        <ul class="list-disc pl-5 my-3">
                            <li>选择了一个背风的位置，水深约2-3米</li>
                            <li>使用的是自制酒米饵料，加了一点蜂蜜</li>
                            <li>鱼竿是碳素5.4米，搭配3号主线和1.5号子线</li>
                            <li>钓点有少量水草，使用了提线钓法</li>
                        </ul>
                        <p>分享几张照片：</p>
                        <div class="grid grid-cols-2 gap-2 my-3">
                            <img src="https://picsum.photos/600/400?fishing1" alt="钓鱼照片" class="rounded-lg">
                            <img src="https://picsum.photos/600/400?fishing2" alt="钓鱼照片" class="rounded-lg">
                        </div>
                        <p>大家有什么好的建议或者想法，欢迎在评论区交流！</p>`,
                author: "钓鱼达人",
                authorAvatar: "https://picsum.photos/id/22/200/200",
                date: "2025-05-01",
                section: "淡水钓鱼",
                sectionId: "freshwater",
                likes: 24,
                comments: [
                    {
                        id: "c1",
                        author: "钓鱼老手",
                        authorAvatar: "https://picsum.photos/id/33/200/200",
                        content: "不错的收获！我也经常去太湖钓鱼，建议可以尝试用蚯蚓做饵，效果也很好。",
                        date: "2025-05-01",
                        likes: 5
                    },
                    {
                        id: "c2",
                        author: "鲫鱼达人",
                        authorAvatar: "https://picsum.photos/id/44/200/200",
                        content: "请问具体是在太湖哪个位置啊？最近我也想去试试。",
                        date: "2025-05-02",
                        likes: 2
                    }
                ],
                views: 156
            },
            {
                id: "2",
                title: "求推荐：适合初学者的海钓装备",
                content: `<p>各位钓友好，我是海钓新手，最近想入手一套适合海钓的装备，但对海钓知识了解不多，希望各位能给点建议。</p>
                        <p>我主要有以下几个问题：</p>
                        <ol class="list-decimal pl-5 my-3">
                            <li>初学者预算2000左右，可以买到什么档次的海竿和轮？</li>
                            <li>海钓主要钓什么类型的鱼？需要准备哪些饵料？</li>
                            <li>有什么注意事项是新手容易忽略的？</li>
                        </ol>
                        <p>感谢各位钓友的建议！</p>`,
                author: "新手钓手",
                authorAvatar: "https://picsum.photos/id/55/200/200",
                date: "2025-05-02",
                section: "海钓",
                sectionId: "sea",
                likes: 15,
                comments: [
                    {
                        id: "c3",
                        author: "海钓老炮",
                        authorAvatar: "https://picsum.photos/id/66/200/200",
                        content: "建议买一根2.7米左右的海竿，搭配一个5000型号的纺车轮。初学者可以先从矶钓开始，比较安全也容易上手。",
                        date: "2025-05-02",
                        likes: 8
                    }
                ],
                views: 98
            }
        ];
        
        localStorage.setItem('forumPosts', JSON.stringify(initialPosts));
    }
    
    // 初始化浏览历史数据
    if (!localStorage.getItem('viewHistory')) {
        const initialHistory = [
            {
                id: "1",
                title: "分享：昨天在太湖钓获的大鲫鱼",
                type: "post",
                url: "post.html?id=1",
                image: "https://picsum.photos/600/400?fishing1",
                date: "2025-05-06T09:30:00.000Z"
            },
            {
                id: "2",
                title: "专业碳素鱼竿",
                type: "product",
                url: "mall.html",
                image: "https://picsum.photos/400/300?rod",
                date: "2025-05-05T14:20:00.000Z"
            }
        ];
        
        localStorage.setItem('viewHistory', JSON.stringify(initialHistory));
    }
    
    // 初始化收藏数据
    if (!localStorage.getItem('favorites')) {
        const initialFavorites = [
            {
                id: "1",
                title: "分享：昨天在太湖钓获的大鲫鱼",
                type: "帖子",
                url: "post.html?id=1",
                image: "https://picsum.photos/600/400?fishing1",
                date: "2025-05-03T11:20:00.000Z"
            },
            {
                id: "2",
                title: "金属轴承渔轮",
                type: "商品",
                url: "mall.html",
                image: "https://picsum.photos/400/300?reel",
                date: "2025-05-04T16:40:00.000Z"
            }
        ];
        
        localStorage.setItem('favorites', JSON.stringify(initialFavorites));
    }
}

/**
 * 设置正在开发中的功能
 * 为页面上的开发中功能按钮添加事件监听器
 */
function setupDevelopmentFeatures() {
    const devFeatureButtons = [
        document.getElementById('communityBtn'),
        document.getElementById('techniqueBtn'),
        document.getElementById('fishingMapBtn'),
        document.getElementById('eventsBtn')
    ];
    
    const devModal = document.getElementById('development-modal');
    const closeDevModal = document.getElementById('close-dev-modal');
    
    devFeatureButtons.forEach(button => {
        if (button) {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                if (devModal) {
                    devModal.classList.remove('hidden');
                }
            });
        }
    });
    
    if (closeDevModal) {
        closeDevModal.addEventListener('click', function() {
            devModal.classList.add('hidden');
        });
    }
}

/**
 * 初始化通用页面交互
 */
function setupCommonInteractions() {
    // 移动端菜单切换
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    const mobileMenu = document.getElementById('mobile-menu');
    
    if (mobileMenuBtn && mobileMenu) {
        mobileMenuBtn.addEventListener('click', function() {
            if (mobileMenu.classList.contains('hidden')) {
                mobileMenu.classList.remove('hidden');
            } else {
                mobileMenu.classList.add('hidden');
            }
        });
    }
    
    // 记录页面浏览历史
    recordPageView();
}

/**
 * 记录页面浏览历史
 */
function recordPageView() {
    // 获取当前用户
    const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
    if (!user) return; // 未登录用户不记录
    
    // 获取当前页面信息
    const path = window.location.pathname;
    const search = window.location.search;
    
    // 只记录特定页面
    let pageData = null;
    
    // 帖子详情页
    if (path.includes('post.html')) {
        const urlParams = new URLSearchParams(search);
        const postId = urlParams.get('id');
        if (postId) {
            const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
            const post = posts.find(p => p.id === postId);
            if (post) {
                pageData = {
                    id: post.id,
                    title: post.title,
                    type: 'post',
                    url: `post.html?id=${post.id}`,
                    image: post.image || 'https://picsum.photos/600/400?fishing' + post.id,
                    date: new Date().toISOString()
                };
            }
        }
    } 
    // 商品详情页 - 实际项目中可能有专门的商品详情页
    else if (path.includes('mall.html') && search.includes('product=')) {
        const urlParams = new URLSearchParams(search);
        const productId = urlParams.get('product');
        if (productId) {
            const products = JSON.parse(localStorage.getItem('products') || '[]');
            const product = products.find(p => p.id.toString() === productId);
            if (product) {
                pageData = {
                    id: product.id,
                    title: product.name,
                    type: 'product',
                    url: `mall.html?product=${product.id}`,
                    image: product.image,
                    date: new Date().toISOString()
                };
            }
        }
    }
    
    // 如果获取到了页面数据，记录到浏览历史
    if (pageData) {
        let history = JSON.parse(localStorage.getItem('viewHistory') || '[]');
        
        // 检查是否已存在相同项目，如果存在则更新日期
        const existingIndex = history.findIndex(item => 
            item.id === pageData.id && item.type === pageData.type
        );
        
        if (existingIndex !== -1) {
            history.splice(existingIndex, 1); // 移除旧记录
        }
        
        // 添加到历史记录前面
        history.unshift(pageData);
        
        // 限制历史记录数量
        if (history.length > 20) {
            history = history.slice(0, 20);
        }
        
        // 保存到localStorage
        localStorage.setItem('viewHistory', JSON.stringify(history));
    }
}

/**
 * 添加收藏
 * @param {Object} item - 要收藏的项目
 */
function addToFavorites(item) {
    // 获取当前用户
    const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
    if (!user) return false; // 未登录用户不能收藏
    
    // 获取收藏列表
    let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
    
    // 检查是否已收藏
    const existingIndex = favorites.findIndex(fav => 
        fav.id === item.id && fav.type === item.type
    );
    
    if (existingIndex !== -1) {
        return false; // 已收藏
    }
    
    // 添加收藏时间
    item.date = new Date().toISOString();
    
    // 添加到收藏列表
    favorites.unshift(item);
    
    // 保存到localStorage
    localStorage.setItem('favorites', JSON.stringify(favorites));
    
    return true;
}

/**
 * 移除收藏
 * @param {string} id - 收藏项目ID
 * @param {string} type - 收藏项目类型
 */
function removeFromFavorites(id, type) {
    // 获取收藏列表
    let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
    
    // 过滤掉要移除的项目
    favorites = favorites.filter(item => !(item.id === id && item.type === type));
    
    // 保存到localStorage
    localStorage.setItem('favorites', JSON.stringify(favorites));
}

/**
 * 检查是否已收藏
 * @param {string} id - 项目ID
 * @param {string} type - 项目类型
 * @returns {boolean} 是否已收藏
 */
function isFavorited(id, type) {
    const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
    return favorites.some(item => item.id === id && item.type === type);
}

/**
 * 格式化日期
 * @param {string} dateString - ISO日期字符串
 * @param {boolean} includeTime - 是否包含时间
 * @returns {string} 格式化的日期字符串
 */
function formatDate(dateString, includeTime = false) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    
    // 今天的日期
    if (date.toDateString() === now.toDateString()) {
        return includeTime ? 
            `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}` : 
            '今天';
    }
    
    // 昨天的日期
    const yesterday = new Date();
    yesterday.setDate(now.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
        return includeTime ? 
            `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}` : 
            '昨天';
    }
    
    // 其他日期
    const options = { year: 'numeric', month: 'long', day: 'numeric' };
    if (includeTime) {
        return `${date.toLocaleDateString('zh-CN', options)} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else {
        return date.toLocaleDateString('zh-CN', options);
    }
}

/**
 * 获取URL参数
 * @param {string} name - 参数名
 * @returns {string|null} 参数值
 */
function getUrlParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}